﻿let echarts_1_data = [];
let echarts_1_value = [];
let echarts_2_data = [];
let echarts_2_value = [];
let echarts_4_type = [];
let echarts_4_data = [];
let echarts_5_type = [];
let echarts_5_data = [];
let echarts_6_type = [];
let echarts_6_data = [];

let echarts_3_type = [];
let echarts_3_data = [];

// 初始化时获取配置
const Year = localStorage.getItem("selectedYear");
const api = localStorage.getItem("api") || "";

$(function () {
  // 初始化所有图表实例
  var myChart1 = echarts.init(document.getElementById("echart1"));
  var myChart2 = echarts.init(document.getElementById("echart2"));
  var myChart3 = echarts.init(document.getElementById("echart3"));
  var myChart4 = echarts.init(document.getElementById("echart4"));
  var myChart5 = echarts.init(document.getElementById("echart5"));
  var myChart6 = echarts.init(document.getElementById("echart6"));

  // 全局 resize 事件监听
  window.addEventListener("resize", function() {
    myChart1.resize();
    myChart2.resize();
    myChart3.resize();
    myChart4.resize();
    myChart5.resize();
    myChart6.resize();
  });

  function echarts_1() {
    option = {
      //  backgroundColor: '#00265f',
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "3%",
        top: "20%",    // 增加更多顶部空间
        right: "3%",
        bottom: "4%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: echarts_1_data,
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
              width: 1,
              type: "solid",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            interval: 0,
            rotate: 15,    // 旋转标签
            show: true,
            splitNumber: 15,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          axisLabel: {
            //formatter: '{value} %'
            show: true,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1	)",
              width: 1,
              type: "solid",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(255,255,255,.1)",
            },
          },
        },
      ],
      series: [
        {
          type: "bar",
          data: echarts_1_value,
          barWidth: "35%", //柱子宽度
          // barGap: 1, //柱子之间间距
          itemStyle: {
            normal: {
              color: "#2f89cf",
              opacity: 1,
              barBorderRadius: 5,
            },
          },
          label: {
            show: true,
            position: "top",
            distance: 20,    // 增加标签距离
            textStyle: {
              color: "#fff",
              fontSize: "12",  // 稍微减小字号
              fontWeight: "bold"
            },
            formatter: function(params) {
              if (params.value >= 10000) {
                return (params.value/10000).toFixed(2) + '万';
              }
              return params.value.toFixed(2);
            }
          }
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart1.setOption(option);
  }

  function get_user_consumption() {
    // console.log(token)
    fetch(api + "/bigscreen/agriculturalyield/top10", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        year: Year,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        // console.log(data);
        // 同时提取分类名称和数值
        echarts_1_data = data.map((item) => item.indicator);
        echarts_1_value = data.map((item) => item.value);

        // console.log(echarts_1_data);
        // console.log(echarts_1_value);
        // 更新图表配置
        myChart1.setOption({
          xAxis: [
            {
              data: echarts_1_data, // 更新分类数据
            },
          ],
          series: [
            {
              data: echarts_1_value, // 更新数值数据
            },
          ],
        });
      })

      .catch((error) => console.error("请求失败:", error));
  }

  // 立即获取数据
  get_user_consumption();

  function echarts_2() {
    option = {
      //  backgroundColor: '#00265f',
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
      },
      grid: {
        left: "3%",
        top: "20%",    // 增加更多顶部空间
        right: "3%",
        bottom: "4%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: echarts_2_data,
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
              width: 1,
              type: "solid",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            interval: 0,
            rotate: 15,    // 旋转标签
            show: true,
            splitNumber: 15,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          axisLabel: {
            //formatter: '{value} %'
            show: true,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1	)",
              width: 1,
              type: "solid",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(255,255,255,.1)",
            },
          },
        },
      ],
      series: [
        {
          type: "bar",
          data: echarts_2_value,
          barWidth: "35%", //柱子宽度
          // barGap: 1, //柱子之间间距
          itemStyle: {
            normal: {
              color: "#27d08a",
              opacity: 1,
              barBorderRadius: 5,
            },
          },
          label: {
            show: true,
            position: "top",
            distance: 20,    // 增加标签距离
            textStyle: {
              color: "#fff",
              fontSize: "12",  // 稍微减小字号
              fontWeight: "bold"
            },
            formatter: function(params) {
              if (params.value >= 10000) {
                return (params.value/10000).toFixed(2) + '万';
              }
              return params.value.toFixed(2);
            }
          }
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart2.setOption(option);
  }
  function get_user_product_preference() {
    fetch(api + "/bigscreen/plantingArea/top10", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        year: Year,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        // console.log(data);
        // 同时提取分类名称和数值
        echarts_2_data = data.map((item) => item.indicator);
        echarts_2_value = data.map((item) => item.value);
        // console.log(echarts_2_data);
        // console.log(echarts_2_value);
        // 更新图表配置

        myChart2.setOption({
          xAxis: [
            {
              data: echarts_2_data, // 更新分类数据
            },
          ],
          series: [
            {
              data: echarts_2_value, // 更新数值数据
            },
          ],
        });
      })
      .catch((error) => console.error("请求失败:", error));
  }
  // 立即获取数据
  get_user_product_preference();
  // 设置定时器（每1秒更新）

  function echarts_4() {
    let fullData = [];  // 存储完整数据
    let currentData = [];  // 存储当前显示的数据

    option = {
      backgroundColor: 'transparent',
      title: {
  
        textStyle: {
          color: '#fff',
          fontSize: 16
        },
        left: 'center',
        top: 10
      },
      grid: {
        top: '15%',
        bottom: '15%',
        left: '8%',
        right: '8%'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        data: [],
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255,255,255,.1)',
            width: 1
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: 'rgba(255,255,255,.6)',
          fontSize: 12,
          rotate: 30
        }
      },
      yAxis: {
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255,255,255,.1)',
            type: 'dashed'
          }
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255,255,255,.1)',
            width: 1
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: 'rgba(255,255,255,.6)',
          fontSize: 12,
          formatter: function(value) {
            if (value >= 10000) {
              return (value/10000).toFixed(1) + '万';
            }
            return value;
          }
        }
      },
      series: [
        {
          type: 'bar',
          name: '产量',
          barWidth: '25%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#00ffff' },
              { offset: 1, color: '#0080ff' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          data: []
        },
        {
          type: 'line',
          name: '趋势',
          smooth: true,
          showSymbol: false,
          lineStyle: {
            width: 3,
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#ff3333' },
              { offset: 1, color: '#ff9933' }
            ])
          },
          itemStyle: {
            color: '#ff3333'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(255,51,51,0.3)' },
              { offset: 1, color: 'rgba(255,51,51,0.1)' }
            ])
          },
          data: []
        }
      ],
      animationDuration: 1000,
      animationEasing: 'cubicInOut'
    };

    myChart4.setOption(option);

    function updateChart4Data() {
      fetch(api + "/bigscreen/agriculturalYield/all", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ year: Year }),
      })
        .then((response) => response.json())
        .then((data) => {
          // 初始化数据
          fullData = data.sort((a, b) => b.value - a.value);
          currentData = [...fullData];
          
          function updateChart() {
            if (currentData.length === 0) {
              currentData = [...fullData];  // 重置数据
            }

            let xData = currentData.map(item => item.indicator);
            let yData = currentData.map(item => item.value);

            myChart4.setOption({
              xAxis: {
                data: xData
              },
              series: [
                {
                  data: yData
                },
                {
                  data: yData
                }
              ]
            });

            // 移除最大值
            currentData.shift();
          }

          // 初始更新
          updateChart();

          // 定时更新
          setInterval(updateChart, 3000);
        })
        .catch((error) => console.error("请求失败:", error));
    }

    updateChart4Data();
  }

  function echarts_5() {
    let currentIndex = 0;
    let allData = [];
    let allTypes = [];

    option = {
      backgroundColor: 'transparent',
      title: {
        left: 'center',
        top: 10,
        textStyle: {
          color: '#fff',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} 千公顷 ({d}%)',
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: '#1E90FF',
        borderWidth: 1,
        padding: [8, 12]
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: '2%',
        top: 'middle',
        itemWidth: 12,
        itemHeight: 12,
        itemGap: 12,
        textStyle: {
          color: 'rgba(255,255,255,.7)',
          fontSize: 14
        },
        pageTextStyle: {
          color: 'rgba(255,255,255,.7)'
        },
        formatter: function(name, params) {
          // 从 series.data 中找到对应的数据
          let data = option.series[0].data;
          let item = data.find(item => item.name === name);
          let value = item ? item.value : 0;
          
          return value >= 10000 ? 
            name + ': ' + (value/10000).toFixed(1) + '万' :
            name + ': ' + value.toFixed(1);
        }
      },
      series: [
        {
          name: '播种面积',
          type: 'pie',
          radius: ['40%', '75%'],
          center: ['45%', '50%'],
          roseType: false,
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#0c4163',
            borderWidth: 2
          },
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              formatter: function(params) {
                return params.value >= 10000 ?
                  (params.value/10000).toFixed(1) + '万' :
                  params.value.toFixed(1);
              },
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: []
        }
      ],
      color: [
        '#4992ff',
        '#7cffb2',
        '#fddd60',
        '#ff6e76',
        '#58d9f9',
        '#05c091',
        '#ff8a45',
        '#8d48e3'
      ]
    };

    myChart5.setOption(option);

    window.updateChart5 = function(data, types) {
      // 保存数据到全局变量
      allData = data;
      allTypes = types;

      // 对数据进行排序，只显示前8个，其余归为"其他"
      let sortedData = types.map((type, index) => ({
        name: type,
        value: data[index]
      })).sort((a, b) => b.value - a.value);

      let top8 = sortedData.slice(0, 8);
      let others = sortedData.slice(8);
      
      if (others.length > 0) {
        let othersSum = others.reduce((sum, item) => sum + item.value, 0);
        top8.push({
          name: '其他',
          value: othersSum
        });
      }

      // 更新图表配置
      option.series[0].data = top8;
      myChart5.setOption(option);

      // 自动轮播效果
      clearInterval(window.chart5Timer);
      window.chart5Timer = setInterval(() => {
        const dataLen = top8.length;
        currentIndex = (currentIndex + 1) % dataLen;
        
        myChart5.dispatchAction({
          type: 'downplay',
          seriesIndex: 0
        });
        
        myChart5.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: currentIndex
        });
        
        myChart5.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: currentIndex
        });
      }, 3000);
    };
  }

  // 数据获取函数（保持原有调用）
  function get_user_payment_preference() {
    fetch(api + "/bigscreen/plantingArea/all", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year: Year }),
    })
      .then((response) => response.json())
      .then((data) => {
        const validData = data.slice(0, -1);
        window.updateChart5(
          validData.map((item) => Number(item.value.toFixed(2))),
          validData.map((item) => item.indicator)
        );
      })
      .catch((error) => console.error("请求失败:", error));
  }
  get_user_payment_preference();

  function echarts_6() {
    var option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },

      grid: {
        left: "3%",     // 增加左边距
        top: "10px",
        right: "3%",
        bottom: "4%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: [],
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(255,255,255,.1)",
            width: 1,
            type: "solid",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          show: true,
          splitNumber: 15,
          textStyle: {
            color: "rgba(255,255,255,.6)",
            fontSize: "12",
          },
        },
      },
      yAxis: {
        type: "value",
        axisLabel: {
          show: true,
          textStyle: {
            color: "rgba(255,255,255,.6)",
            fontSize: "12",
          },
        },
        axisTick: {
          show: false,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(255,255,255,.1)",
            width: 1,
            type: "solid",
          },
        },
        splitLine: {
          lineStyle: {
            color: "rgba(255,255,255,.1)",
          },
        },
      },
      series: [
        {
          name: "数据",
          type: "line",
          smooth: true,
          symbol: "circle",
          symbolSize: 8,
          lineStyle: {
            color: "#2f89cf",
            width: 2,
          },
          label: {
            show: true,
            position: function(params) {
              // 第一个数据点标签位置调整到右上方
              return params.dataIndex === 0 ? 'right' : 'top';
            },
            distance: 10,
            textStyle: {
              color: "rgba(255,255,255,.8)",
              fontSize: "12",
            },
            formatter: function(params) {
              return params.value.toFixed(2);
            }
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgba(47,137,207,0.8)",
              },
              {
                offset: 1,
                color: "rgba(47,137,207,0.1)",
              },
            ]),
          },
          data: [],
        },
      ],
    };
    myChart6.setOption(option);
  }
  function get_user_basic_info_membership_level() {
    fetch(api + "/bigscreen/affected_area/all", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year: Year }),
    })
      .then((response) => response.json())
      .then((data) => {
        // 将数据转换为正确的格式，包含 name 和 value
        echarts_6_type = data.map((item) => item.indicator);
        echarts_6_data = data.map((item) => item.value);

        // 更新图表配置
        myChart6.setOption({
          xAxis: {
            data: echarts_6_type,
          },
          series: [
            {
              data: echarts_6_data,
            },
          ],
        });
      })
      .catch((error) => console.error("请求失败:", error));
  }
  get_user_basic_info_membership_level();

  function echarts_3() {
    option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "0%", // 增加左边距
        top: "10px",
        right: "10%", // 增加右边距
        bottom: "4%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "value",
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
              width: 1,
              type: "solid",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
              type: "dashed"
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
            formatter: function(value) {
              if (value >= 10000) {
                return (value/10000).toFixed(1) + '万';
              }
              return value;
            },
            interval: 'auto',
            margin: 8
          },
          max: function(value) {
            return value.max + (value.max * 0.1);
          }
        },
      ],
      yAxis: [
        {
          type: "category",
          data: [],
          axisLabel: {
            show: true,
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255,255,255,.1)",
              width: 1,
              type: "solid",
            },
          },
        },
      ],
      series: [
        {
          type: "bar",
          data: [],
          barWidth: "35%",
          label: {
            show: true,
            position: "right",
            textStyle: {
              color: "rgba(255,255,255,.6)",
              fontSize: "12",
            },
          },
          itemStyle: {
            normal: {
              color: "#2f89cf",
              opacity: 1,
              barBorderRadius: 5,
            },
          },
        },
      ],
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart3.setOption(option);
  }

  function get_contrast() {
    // console.log(token)
    fetch(api + "/bigscreen/contrast", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        year: Year,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        echarts_3_data = ["产量", "受灾面积", "种植"];
        echarts_3_value = [
          data["产量(万吨)"],
          data["受灾面积(千公顷)"],
          data["种植面积(千公顷)"],
        ];
		document.getElementById("shishi").innerHTML =data["种植面积(千公顷)"] ;
		document.getElementById("shishixiaoshou").innerHTML = data["产量(万吨)"] ;
        // console.log(echarts_3_data);
        // console.log(echarts_3_value);

        // 更新图表配置
        myChart3.setOption({
          yAxis: [
            {
              data: echarts_3_data, // 将类别数据更新到 y 轴
            },
          ],
          series: [
            {
              data: echarts_3_value, // 更新数值数据
            },
          ]
        });
      })

      .catch((error) => console.error("请求失败:", error));
  }

  // 立即获取数据
  get_contrast();

  // 初始化所有图表
  echarts_1();
  echarts_2();
  echarts_3();
  echarts_4();
  echarts_5();
  echarts_6();
});
